package com.atguigu.gmall.util.service.impl;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.util.service.RabbitService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.IOException;

/**
 * @author lfy
 * @Description
 * @create 2022-10-22 11:59
 */
@Slf4j
public class RabbitServiceImpl implements RabbitService {

    @Autowired
    StringRedisTemplate redisTemplate;

    public void retry(Channel channel,Long deliveryTag,String msgContent,int count ) throws IOException {
        String md5 = MD5.encrypt(msgContent);
        //给redis添加一次重试记录。  mq:retrycount:每个消息md5 =
        Long increment = redisTemplate.opsForValue().increment(RedisConst.MQ_RETRY + md5);
        if(increment <= count){
            log.error("消息消费失败:{}，正在重试第 {} 次；并返给队列：",msgContent,increment);
            channel.basicNack(deliveryTag,false,true);
        }else {
            log.error("消费重试超过最大次数，消息保存到告警库等待人工处理: {}",msgContent);
            redisTemplate.delete(RedisConst.MQ_RETRY + md5);
        }
    }
}
